package com.cfl.springboot.controller;

import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cfl.springboot.model.User;
import com.cfl.springboot.model.vo.UserVo;
import com.cfl.springboot.service.UserService;
import com.cfl.springboot.utils.AppResponse;
import com.sun.org.apache.bcel.internal.generic.NEW;

@Controller
@RequestMapping("/user/")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("login")
	@ResponseBody
	public Object login(User user)
	{
		if(user == null || StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPassword()))
		{
			return new AppResponse("-1", "用户名或密码为空");
		}
		try {
			int status = userService.login(user.getName(), user.getPassword());
			if(status != 0)
			{
				return new AppResponse("-1", "用户名或密码错误");
			}
			User loginUser = userService.findByName(user.getName());
			return new AppResponse(new UserVo(loginUser));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AppResponse();
	}
	
	@RequestMapping("register")
	@ResponseBody
	public Object register(User user)
	{
		if(user == null || StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPassword()))
		{
			return new AppResponse("-1", "用户名或密码为空");
		}
		try {
			userService.saveRegister(user.getName(), user.getPassword());
			User tempUser = userService.findByName(user.getName());
			if(tempUser == null)
			{
				return new AppResponse("-1", "系统繁忙");
			}
			return new AppResponse(new UserVo(userService.findByName(user.getName())));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AppResponse();
	}
}
